package com.mingqijia.gassafety.webserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.db.entity.FieldListShow;
import com.mingqijia.gassafety.db.mapper.FieldListShowMapper;
import com.mingqijia.gassafety.shared.user.UserBackend;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.webserver.request.AddFieldShowRequest;
import com.mingqijia.gassafety.webserver.request.FieldListShowRequest;
import com.mingqijia.gassafety.webserver.request.UpdateListShowRequest;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.service.FieldListShowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统列表字段自定义 服务实现类
 * </p>
 *
 * @author fei.zhang
 * @since 2023-09-22
 */
@Service
@Slf4j
public class FieldListShowServiceImpl extends ServiceImpl<FieldListShowMapper, FieldListShow> implements FieldListShowService {


    @Autowired
    private FieldListShowMapper fieldListShowMapper;

    /**
     * 查询企业列表字段配置
     *
     * @return
     */
    @Override
    public List<FieldListShowResponse> queryListShow(String listCode, String spId) {
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        String username = workingUser.getUsername();
        List<FieldListShowResponse> responses = new ArrayList<>();
        if (StringUtils.isEmpty(spId)) spId =username;
        LambdaQueryWrapper<FieldListShow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FieldListShow::getSpId, spId).eq(FieldListShow::getIsDeleted, 0)
        .orderByAsc(FieldListShow::getFieldSort);
        if (!StringUtils.isEmpty(listCode)) queryWrapper.eq(FieldListShow::getListCode, listCode);
        List<FieldListShow> fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(fieldListShows)) {
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.or().eq(FieldListShow::getIsDeleted, 0)
                    .eq(FieldListShow::getSpId, "system");
            if (!StringUtils.isEmpty(listCode)) queryWrapper.eq(FieldListShow::getListCode, listCode);
            queryWrapper.orderByAsc(FieldListShow::getFieldSort);
            fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        }
        fieldListShows.forEach(fieldListShow -> {
            FieldListShowResponse fieldListShowResponse = new FieldListShowResponse();
            BeanUtils.copyProperties(fieldListShow, fieldListShowResponse);
            String fieldName = fieldListShowResponse.getFieldName();
            if (fieldName.contains("|")) {
                fieldListShowResponse.setFieldName(fieldName.replace("|", ""));
            }
            responses.add(fieldListShowResponse);
        });
        return responses;
    }


    /**
     * 更新企业列表字段配置
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addListShow(UpdateListShowRequest request) {
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        String username = workingUser.getUsername();
        log.info("updateListShow-request:{},username:{}", JSONObject.toJSONString(request),username);
        String spId = username;
        List<FieldListShowRequest> listShowRequests = request.getListShowRequests();
        //判断企业是否配置过
        LambdaQueryWrapper<FieldListShow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FieldListShow::getSpId, spId).eq(FieldListShow::getIsDeleted, 0)
                .eq(FieldListShow::getListCode, request.getListCode());
        List<FieldListShow> fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        log.info("updateListShow-fieldListShows:{}", JSONObject.toJSONString(fieldListShows));
        if (CollectionUtils.isEmpty(fieldListShows)) {
            fieldListShowMapper.copyDataBySpid(spId);
            LambdaUpdateWrapper<FieldListShow> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.or().eq(FieldListShow::getIsDeleted, 0).eq(FieldListShow::getSpId, spId);
            for (int i = 0; i < listShowRequests.size(); i++) {
                FieldListShowRequest fieldListShowRequest = listShowRequests.get(i);
                LambdaUpdateWrapper<FieldListShow> updateWrapperCopy = updateWrapper;
                FieldListShow fieldListShow = new FieldListShow();
                BeanUtils.copyProperties(fieldListShowRequest, fieldListShow);
                fieldListShow.setSpId(spId);
                fieldListShow.setFieldSort(i+1);
                updateWrapperCopy.eq(FieldListShow::getFieldCode, fieldListShow.getFieldCode())
                        .eq(FieldListShow::getSpId,spId);
                if (!StringUtils.isEmpty(fieldListShowRequest.getFieldSort()))
                    updateWrapperCopy.set(FieldListShow::getFieldSort, fieldListShow.getFieldSort());
                updateWrapperCopy.set(FieldListShow::getShowStatus, fieldListShow.getShowStatus());
                fieldListShowMapper.update(fieldListShow, updateWrapperCopy);
            }
            return;
        }
        if (!spId.equals(fieldListShowMapper.selectById(listShowRequests.get(0).getId()).getSpId())){
            fieldListShowMapper.updateDataBySpid(spId,request.getListCode());
            for (int j = 0; j < listShowRequests.size(); j++) {
                FieldListShowRequest fieldListShowRequest = listShowRequests.get(j);
                log.info("fieldListShowMapper-update:{}",JSONObject.toJSONString(fieldListShowRequest));
                fieldListShowMapper.updateDataBySpidAndListCode(spId,request.getListCode(),fieldListShowRequest.getFieldCode()
                        ,j+1,fieldListShowRequest.getShowStatus());
            }
            if (listShowRequests.size()!=fieldListShows.size()
                    &&listShowRequests.size()-fieldListShows.size()>0){
                int j=fieldListShows.size();
                for (int i = 0; i < listShowRequests.size() - fieldListShows.size(); i++) {
                    FieldListShow field = fieldListShowMapper.selectById(listShowRequests.get(j).getId());
                    if (field==null) return;
                    FieldListShow fieldListShow = new FieldListShow();
                    BeanUtils.copyProperties(field,fieldListShow);
                    fieldListShow.setSpId(spId);
                    fieldListShow.setId(null);
                    fieldListShowMapper.insert(fieldListShow);
                    j++;
                }
            }
            return;
        }
        for (int i = 0; i < listShowRequests.size(); i++) {
            FieldListShowRequest fieldListShowRequest=listShowRequests.get(i);
            FieldListShow fieldListShow = new FieldListShow();
            BeanUtils.copyProperties(fieldListShowRequest, fieldListShow);
            fieldListShow.setSpId(spId);
            fieldListShow.setFieldSort(i+1);
            fieldListShowMapper.updateById(fieldListShow);
        }

    }

    /**
     * 判断动态列表字段是否加载
     *
     * @param spId
     * @return
     */
    @Override
    public List<Integer> loadField(String listCode, String spId) {
        List<Integer> res = new ArrayList<>();
        LambdaQueryWrapper<FieldListShow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FieldListShow::getSpId, spId).eq(FieldListShow::getIsDeleted, 0);
        List<FieldListShow> fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        log.info("loadField-fieldListShows:{}", JSON.toJSON(fieldListShows));
        if (CollectionUtils.isEmpty(fieldListShows))spId="system";
        res = fieldListShowMapper.selectCategory(listCode, spId);
        log.info("loadField-res:{}", JSON.toJSON(res));
        return res;
    }

    /**
     * 获取页面展示自定义字段
     *
     * @param listCode
     * @param spId
     * @return
     */
    @Override
    public List<FieldListShowResponse> queryListShowByShowStatus(String listCode, String spId) {
        try {
            spId=  ApplicationUtils.getWorkingUser().getUsername();
        } catch (Exception e) {
            log.error("不需要登录的接口",e);
            return new ArrayList<FieldListShowResponse>();
        }
        List<FieldListShowResponse> responses = new ArrayList<>();
        LambdaQueryWrapper<FieldListShow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FieldListShow::getSpId, spId).eq(FieldListShow::getIsDeleted, 0)
                .orderByAsc(FieldListShow::getFieldSort);
        queryWrapper.eq(FieldListShow::getListCode, listCode).eq(FieldListShow::getShowStatus, 0);
        List<FieldListShow> fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(fieldListShows)) {
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.or().eq(FieldListShow::getIsDeleted, 0)
                    .eq(FieldListShow::getSpId, "system");
            queryWrapper.eq(FieldListShow::getListCode, listCode).eq(FieldListShow::getShowStatus, 0);
            queryWrapper.orderByAsc(FieldListShow::getFieldSort);
            fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        }
        fieldListShows.forEach(fieldListShow -> {
            FieldListShowResponse fieldListShowResponse = new FieldListShowResponse();
            BeanUtils.copyProperties(fieldListShow, fieldListShowResponse);
            String fieldName = fieldListShowResponse.getFieldName();
            if (fieldName.contains("|")) {
                fieldListShowResponse.setFieldName(fieldName.substring(0,fieldName.indexOf("|")));
            }
            responses.add(fieldListShowResponse);
        });
        return responses;
    }

    @Override
    public void updateConfig(UpdateListShowRequest request) {
        List<FieldListShowRequest> listShowRequests = request.getListShowRequests();
        listShowRequests.forEach(showRequest ->{
            FieldListShow fieldListShow = new FieldListShow();
            fieldListShow.setId(showRequest.getId());
            fieldListShow.setFieldCode(showRequest.getFieldCode());
            fieldListShow.setFieldName(showRequest.getFieldName());
            fieldListShowMapper.updateById(fieldListShow);
        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addListShow(AddFieldShowRequest request) {
        LambdaQueryWrapper<FieldListShow> queryWrapper = new LambdaQueryWrapper<>();
        List<FieldListShow> fieldListShows;
        //根据传入的账号进行查询，没有取默认system
        if (!StringUtils.isEmpty(request.getAccount())) {
            queryWrapper.eq(FieldListShow::getSpId, request.getAccount()).eq(FieldListShow::getIsDeleted, 0)
                    .orderByAsc(FieldListShow::getFieldSort);
            fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        } else {
            queryWrapper.eq(FieldListShow::getSpId, "system").eq(FieldListShow::getIsDeleted, 0)
                    .orderByAsc(FieldListShow::getFieldSort);
            fieldListShows = fieldListShowMapper.selectList(queryWrapper);
        }
        //当传入账号没有数据时直接返回
        if (CollectionUtils.isEmpty(fieldListShows)) {
            return;
        }

        //根据要生产账号查询是否有数据，有的话需要把们没有字段补上，没有需要新增
        LambdaQueryWrapper<FieldListShow> fieldListWrapper = new LambdaQueryWrapper<>();
        fieldListWrapper.in(FieldListShow::getSpId, request.getSpId()).eq(FieldListShow::getIsDeleted, 0)
                .orderByAsc(FieldListShow::getFieldSort);
        List<FieldListShow> listShowList = fieldListShowMapper.selectList(fieldListWrapper);
        List<FieldListShow> fieldListShowList = new ArrayList<>();
        Map<String, List<FieldListShow>> listShowMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(listShowList)) {
            //根据spid进行分组
            listShowMap = listShowList.stream().collect(Collectors.groupingBy(FieldListShow::getSpId));
        }

        for (String spId : request.getSpId()) {
            if (listShowMap.containsKey(spId)) {
                List<FieldListShow> listShows = listShowMap.get(spId);
                //根据列表页和属性值进行分组，每个列表判断进行新增
                Map<String, FieldListShow> fieldListMap = listShows.stream().collect(Collectors.toMap(e -> e.getListCode() + "-" + e.getFieldCode(), FieldListShow -> FieldListShow, (n1, n2) -> n1));
                for (FieldListShow fieldListShow : fieldListShows) {
                    //当需要生成的账号中有，当前账号没有时需要新增
                    if (!fieldListMap.containsKey(fieldListShow.getListCode() + "-" + fieldListShow.getFieldCode())) {
                        FieldListShow listShow = new FieldListShow();
                        BeanUtils.copyProperties(fieldListShow, listShow);
                        listShow.setId(null);
                        listShow.setSpId(spId);
                        fieldListShowList.add(listShow);
                    }
                }
            } else {
                for (FieldListShow fieldListShow : fieldListShows) {
                    FieldListShow listShow = new FieldListShow();
                    BeanUtils.copyProperties(fieldListShow, listShow);
                    listShow.setId(null);
                    listShow.setSpId(spId);
                    fieldListShowList.add(listShow);
                }
            }
        }
        this.saveBatch(fieldListShowList);
    }

}
